package com.atcjx.service;

import com.atcjx.MyUtils.File.FileUtils;
import com.atcjx.MyUtils.IdUtils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @author: tlw
 * @date: 2021年10月12日
 * @Description: COS对象存储
 */
@Service
public class TencentCDNServiceImpl {
    private static final Logger LOG = LoggerFactory.getLogger(TencentCDNServiceImpl.class);

    @Value("${cos.accessKey}")
    private String accessKey;

    @Value("${cos.secretKey}")
    private String secretKey;

    @Value("${cos.regionName}")
    private String regionName;

    @Value("${cos.bucketName}")
    private String bucketName;

    @Value("${cos.keyName}")
    private String keyName;

    /**
     * @Author Cjx_71023
     * @Description //TODO 上传图片到腾讯云图床
     * @Date 22:55 2022/3/26
     * @Param [fileDataFileName, request, response]
     * @return java.lang.String
     **/
    public String contentCOS(MultipartFile fileDataFileName, HttpServletRequest request, HttpServletResponse response) {
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(regionName));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);

        // 获取文件类型
        String name = fileDataFileName.getOriginalFilename();
        String fileType = name.substring(name.lastIndexOf(".") + 1);

        // bucket名需包含appid
        String key = keyName + "/" + IdUtils.getRandomStringId() + "." + fileType;
        String url = null;
        try {
            // 处理文件路径
            String filePath = request.getSession().getServletContext().getRealPath("/") + fileDataFileName.getOriginalFilename();
            fileDataFileName.transferTo(new File(filePath));
            File localFile = new File(filePath);

            // 报错请求对象
            AppendObjectRequest appendObjectRequest = new AppendObjectRequest(bucketName, key, localFile);
            // 设置节点
            appendObjectRequest.setPosition(0L);
            AppendObjectResult appendObjectResult = cosclient.appendObject(appendObjectRequest);
            // 文件大小
            long nextAppendPosition = appendObjectResult.getNextAppendPosition();
            LOG.info("文件大小：{}", nextAppendPosition);

            // 获取返回对象
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
            COSObject cosObject = cosclient.getObject(getObjectRequest);
            url = cosObject.getObjectContent().getHttpRequest().getURI().toString();
        } catch (CosClientException | IOException e) {
            e.printStackTrace();
        } finally {
            cosclient.shutdown();
        }
        return url;
    }

    public String contentCOSByURL(String url, HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartFile file = FileUtils.urlToMultipartFile(url);
        return contentCOS(file, request, response);
    }
}
